package com.lock.method;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName:com.lock.method
 * @ClassName:Test03
 * @Description:   boolean hasQueueThread(Thread thread)  查询参数指定的线程是否在等待获得锁
 *                 boolean hasQueueThread() 查询是否还有线程在等待获得锁
 * @Author: zhangxiaoyu
 * @date 2021/3/8 13:08
 */
public class Test03 {

    static  ReentrantLock lock = new ReentrantLock();//定义锁

    public  static void waitMethod(){

        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"获得锁");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName()+"释放了锁对象-----");
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
         Runnable r = new Runnable() {
             @Override
             public void run() {
                 Test03.waitMethod();
             }
         };

         //定义一个线程数组，给数组的元素赋值，每个线程都调用方法，并启动线程
         Thread [] threads = new Thread[5];

         for (int i = 0;i<threads.length;i++){
             threads[i] = new Thread(r);
             threads[i].setName("thread--"+i);
             threads[i].start();
         }

         Thread.sleep(3000);
         //判断数组中的每个线程对象是否在等待获得锁
        System.out.println(lock.hasQueuedThread(threads[0]));
        System.out.println(lock.hasQueuedThread(threads[1]));
        System.out.println(lock.hasQueuedThread(threads[2]));
        System.out.println(lock.hasQueuedThread(threads[3]));
        System.out.println(lock.hasQueuedThread(threads[4]));

        Thread.sleep(2000);
        //判断是否还有线程在等待获得锁

        System.out.println(lock.hasQueuedThreads());

    }

}
